<template>
  <div class="query-container">
    <el-card class="query-editor">
      <template #header>
        <div class="card-header">
          <span>SQL编辑器</span>
          <el-button type="primary" @click="executeQuery">执行</el-button>
        </div>
      </template>
      <el-form :model="queryForm" label-width="80px">
        <el-form-item label="选择连接">
          <el-select v-model="queryForm.connectionId" placeholder="请选择数据库连接">
            <el-option
              v-for="conn in connections"
              :key="conn.id"
              :label="conn.name"
              :value="conn.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SQL语句">
          <el-input
            v-model="queryForm.sql"
            type="textarea"
            :rows="10"
            placeholder="请输入SQL语句"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="query-result" v-if="queryResult">
      <template #header>
        <div class="card-header">
          <span>查询结果</span>
        </div>
      </template>
      <el-table 
        :data="queryResult" 
        style="width: 100%"
        :row-style="{height: '40px'}"
        border
        highlight-current-row
        @cell-click="handleCellClick"
      >
        <el-table-column
          v-for="column in columns"
          :key="column"
          :prop="column"
          :label="column"
          :min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div class="cell-content" :title="scope.row[column]">
              {{ scope.row[column] }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 单元格内容弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentCell?.column?.label"
      width="50%"
      destroy-on-close
    >
      <div class="cell-dialog-content">
        {{ currentCell?.value }}
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { connectionApi, queryApi } from '@/api'

const connections = ref([])
const queryForm = ref({
  connectionId: '',
  sql: ''
})
const queryResult = ref(null)
const columns = ref([])
const dialogVisible = ref(false)
const currentCell = ref(null)

const loadConnections = async () => {
  try {
    const response = await connectionApi.getAllConnections()
    // 确保返回的是数组
    if (Array.isArray(response.data)) {
      connections.value = response.data
    } else {
      connections.value = []
      ElMessage.warning('获取连接列表失败：返回数据格式不正确')
    }
  } catch (error) {
    ElMessage.error('加载连接列表失败')
  }
}

const executeQuery = async () => {
  if (!queryForm.value.connectionId) {
    ElMessage.warning('请选择数据库连接')
    return
  }

  if (!queryForm.value.sql) {
    ElMessage.warning('请输入SQL语句')
    return
  }

  try {
    const response = await queryApi.execute(queryForm.value.connectionId, queryForm.value.sql)
    queryResult.value = response.data
    if (response.data && response.data.length > 0) {
      columns.value = Object.keys(response.data[0])
    }
  } catch (error) {
    ElMessage.error('执行SQL失败')
  }
}

const handleCellClick = (row, column, cell, event) => {
  currentCell.value = {
    value: row[column.property],
    column: column
  }
  dialogVisible.value = true
}

onMounted(() => {
  loadConnections()
})
</script>

<style scoped>
.query-container {
  padding: 20px;
}

.query-editor {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cell-content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cell-dialog-content {
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style> 